package com.fantasy.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.fantasy.EventListener;
import com.fantasy.R;
import com.fantasy.TaskController;
import com.fantasy.User;
import com.fantasy.WimNotificationManager;
import com.fantasy.service.IRemoteService;
import com.fantasy.service.IRemoteServiceCallback;
import com.fantasy.util.Constant;
import com.fantasy.util.IMUtil;

public class MainWimActivity extends ListActivity {
	private static final String TAG = "MainWimActivity";
	private static final boolean DEBUG = true;

	IRemoteService mService = null;
	private boolean mIsBound = false;
	private static final int DIALOG_QUIT = 0;
	private static final int DIALOG_NEW_MESSAGE = 3;

	private static final int MESSAGE_USER_LOGIN = 1;
	private static final int MESSAGE_USER_QUIT = 2;
	private static final int MESSAGE_RESUME = 5;

	private static final int MENU_QUIT = 4;
	private static final String WIM_SERVICE_NAME = "com.fantasy.service.WimService";

	private ArrayList<String> mUserList = new ArrayList<String>();
	private UIEventListener mListener = new UIEventListener();
	private TaskController mTc;
	private UserAdapter mAdapter;
	private boolean mIm;
	private boolean mWimServiceRunning = false;

	private String mMessageContent = null;
	private String mFromIp = null;
	
	WimNotificationManager mWm;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case MESSAGE_USER_LOGIN:
			case MESSAGE_USER_QUIT:
				mAdapter.notifyDataSetChanged();
				break;
			case MESSAGE_RESUME:
				if (DEBUG) {
					Log.d(TAG,"Wim Resume");
				}
				if (mService != null) {
					String allIp = null;
					try {
						allIp = mService.getIpList();
						Log.d(TAG,"all ip:"+allIp);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
					String ips[] = allIp.split(IMUtil.SPLIT);
					Log.d(TAG,"ips.size:"+ips.length);
					boolean isContain = false;
					for (String ip:ips) {
						Log.d(TAG,"ip is:");
						for (String userIp:mUserList) {
							if (userIp.equals(ip)) {
								isContain = true;
							}
						}
						if (!isContain) {
							mUserList.add(ip);
						}
					}
				}
				mAdapter.notifyDataSetChanged();
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_wim_activity);
		// Intent intent = getIntent();
		mWimServiceRunning = isServiceRunning(this, WIM_SERVICE_NAME);
		if (!mWimServiceRunning)
			startService(new Intent(IRemoteService.class.getName()));

		if (DEBUG) {
			Log.d(TAG, "myself ip address:" + IMUtil.getHostIPAddress());
		}
		mWm = new WimNotificationManager(this);
		mAdapter = new UserAdapter(MainWimActivity.this, mUserList);
		// startTask();
		initView();
		// initData();
		// start();
	}

	private void startTask() {
		mTc = TaskController.getInstance();
		if (DEBUG)
			Log.d(TAG, "register:listener");
		mTc.registerObserver(mListener);
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (DEBUG) {
			Log.d(TAG, "bindWimService:");
		}
		// bindWimService();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent();
		intent.putExtra(MessageBoxActivity.MESSAGE_IP, mUserList
				.get(position));
		if (DEBUG) {
			Log.d(TAG, "onListItemClick:" + mUserList.get(position));
		}
		/*
		 * intent.putExtra(ConversionActivity.TARGET_NAME,
		 * mUserList.get(position).userName);
		 */
		intent.setClass(MainWimActivity.this, MessageBoxActivity.class);
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// return super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_QUIT, 0, getString(R.string.quit_applition));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_QUIT:
			showDialog(DIALOG_QUIT);
			return true;
		}
		return false;
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case DIALOG_QUIT:
			return new AlertDialog.Builder(this).setMessage(
					R.string.tip_dialog_quit).setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							Log.d(TAG, "click ok button:" + which);
							if (!isFinishing()) {
								unbindWimService();
								stopService(new Intent(IRemoteService.class
										.getName()));
								mWm.cancelNotifcation();
								finish();
							}

						}
					}).setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							Log.d(TAG, "click cancel button:" + which);
							return;
						}
					}).create();
		case DIALOG_NEW_MESSAGE:
			return new AlertDialog.Builder(this).setTitle(mFromIp).setMessage(
					mMessageContent).setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

						}
					}).create();
		}

		return super.onCreateDialog(id, args);
	}

	private class UserAdapter extends BaseAdapter {
		LayoutInflater mInflater;
		private Context mContext;
		private ArrayList<String> mUserData;

		public UserAdapter(Context context, ArrayList<String> userlist) {
			mInflater = LayoutInflater.from(context);
			mUserData = userlist;
			mContext = context;
		}

		public int getCount() {
			return mUserData.size();
		}

		@Override
		public void registerDataSetObserver(DataSetObserver observer) {
			super.registerDataSetObserver(observer);

		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mUserData.get(position);
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View v;
			if (convertView == null) {
				v = mInflater.inflate(R.layout.user_item_layout, parent, false);
			} else {
				v = convertView;
			}
			TextView userIpView = (TextView) v.findViewById(R.id.userIp);
			TextView userName = (TextView) v.findViewById(R.id.userName);
			String ip = mUserData.get(position);
			if (userIpView != null) {
				if (DEBUG) {
					Log.d(TAG, "User IP:" + ip);
				}
				userIpView.setText(ip);
			}
			/*if (userName != null) {
				if (DEBUG) {
					Log.d(TAG, "User Name:" + user.userName);
				}
				userName.setText(user.userName);
			}
*/
			return v;
		}

	}

	class IncomingHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (DEBUG) {
				Log.d(TAG, "IncomingHandler:" + msg.what);
			}
			switch (msg.what) {

			}
		}

	}

	private class UIEventListener extends EventListener {

		@Override
		public void addUser(String ip) {
			super.addUser(ip);
			mUserList.add(ip);
			Message msg = new Message();
			msg.arg1 = MESSAGE_USER_LOGIN;
			mHandler.sendMessage(msg);

		}

		@Override
		public void newMessage(String message) {
			super.newMessage(message);
		}

		@Override
		public void onEvent(ArrayList<User> al) {
			// TODO Auto-generated method stub
			super.onEvent(al);
		}

		@Override
		public void removeUser(String ip) {
			// TODO Auto-generated method stub
			super.removeUser(ip);
			mUserList.remove(ip);
			Message msg = new Message();
			msg.arg1 = MESSAGE_USER_QUIT;
			mHandler.sendMessage(msg);
		}

	}

	private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {

		public void valueChanged(int value) throws RemoteException {

		}

		public void rmUser(String ip) throws RemoteException {
			for (String userIp : mUserList) {
				if (userIp.equals(ip)) {
					mUserList.remove(userIp);
				}
			}
			Message msg = new Message();
			msg.arg1 = MESSAGE_USER_QUIT;
			mHandler.sendMessage(msg);
		}

		public void addUser(String ip) throws RemoteException {
			if (DEBUG) {
				Log.d(TAG, "addUsre:" + ip);
			}
			User u = new User();
			u.userIp = ip;
			mUserList.add(ip);
			Message msg = new Message();
			msg.arg1 = MESSAGE_USER_LOGIN;
			mHandler.sendMessage(msg);
		}
	};

	private void bindWimService() {

		bindService(new Intent(IRemoteService.class.getName()), mConnection,
				Context.BIND_AUTO_CREATE);
		
		// startService(new Intent(IRemoteService.class.getName()));
		/*
		 * Context realActivity = this.getParent(); if (realActivity == null) {
		 * realActivity = this; } ContextWrapper cw = new
		 * ContextWrapper(realActivity); cw.bindService(new
		 * Intent(IRemoteService.class.getName()), mConnection,
		 * Context.BIND_AUTO_CREATE);
		 */
		/*
		 * if (mService != null) { try { mService.registerCallback(mCallback); }
		 * catch (RemoteException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); } }
		 */
		mIsBound = true;
	}

	private void unbindWimService() {
		if (mIsBound) {

			if (mService != null) {
				try {
					mService.unregisterCallback(mCallback);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
			unbindService(mConnection);

			// stopService(new Intent(IRemoteService.class.getName()));
			mIsBound = false;
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unbindWimService();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		bindWimService();
	}

	private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder service) {
			if (DEBUG) {
				Log.d(TAG, "onServiceConnected:");
			}
			mService = IRemoteService.Stub.asInterface(service);
			try {
				mService.registerCallback(mCallback);
				if (DEBUG) {
					Log.d(TAG, "startLogin");
				}
				if(!mWimServiceRunning) {
					mService.startLogin();
				} else {
					Message msg = new Message();
					msg.arg1 = MESSAGE_RESUME;
					mHandler.sendMessage(msg);
				}
				
				if (mIm) {
					Message msg = new Message();
					msg.arg1 = MESSAGE_USER_LOGIN;
					mHandler.sendMessage(msg);
				}
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		public void onServiceDisconnected(ComponentName name) {
			mService = null;
		}

	};

	private void initView() {
		setListAdapter(mAdapter);
	}

	protected void onStop() {
		super.onStop();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		/*
		 * switch (keyCode) { case KeyEvent.KEYCODE_BACK: Log.d(TAG,
		 * "@@@@@@@@@@@@@kyeCOde_back");
		 * 
		 * return false; }
		 */
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// mTc.stopAllThread();
		unbindWimService();
	}

	public boolean isServiceRunning(Context mContext, String className) {

		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);
		Log.d(TAG, "isServiceRunning:serviceList.size:" + serviceList.size());
		if (!(serviceList.size() > 0)) {
			return false;
		}
		Log.d(TAG, "@@@@@@@@className:" + className);
		for (int i = 0; i < serviceList.size(); i++) {
			Log.d(TAG, "@@@@@@@@@@@@:::"
					+ serviceList.get(i).service.getClassName());
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;

	}

}
